package com.ldc.api.file;

import com.ldc.api.common.ParamsHolder;
import com.ldc.common.utils.CollectionUtils;
import com.ldc.common.utils.FileUtils;
import com.ldc.common.utils.StringUtils;
import com.ldc.model.base.ApiBean;
import com.ldc.service.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 功能描述
 *
 * @author liudi
 * @since 2023/7/23
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    FileService fileService;


    @PostMapping("/upload")
    public ApiBean<?> upload(HttpServletRequest request, @RequestParam(value = "files") List<MultipartFile> files) throws IOException {

        if (Objects.isNull(files) || CollectionUtils.isEmpty(files)) {
            return ApiBean.failed("failed");
        }
        try {
            for (MultipartFile item : files) {
                if (item == null) {
                    continue;
                }
                byte[] fileBytes = item.getBytes();
                String fileName = FileUtils.getNewFileName(item);
                long fileSize = item.getSize();
                String filePath = FileUtils.getSaveFilePath() + File.separator + fileName;
                FileUtils.saveFile(fileBytes, filePath);
                fileService.save(ParamsHolder.createNewFile(request, filePath, fileName, fileSize));
            }
        } catch (Exception error) {
            return ApiBean.failed(error.getMessage());
        }
        return ApiBean.success("success");
    }

    @GetMapping("/download/{id}")
    public ApiBean<?> download(HttpServletResponse response, @PathVariable(value = "id") String fileId) {
        if (StringUtils.isEmpty(fileId)) {
            return ApiBean.failed();
        }
        com.ldc.model.File file = fileService.findByFileId(fileId);
        if (file == null) {
            return ApiBean.failed();
        }
        FileUtils.downloadFile(response, file.getUrl());
        return ApiBean.success("success");
    }
}
